package handlers

import (
	"data_service/models"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)



// CreateRoomHandler 创建房间
func CreateRoomHandler(c *gin.Context) {
	var req struct {
		Name string `json:"name" binding:"required"`
		Tag  string `json:"tag"`
	}
	if err := c.ShouldBindJSON(&req); err != nil || req.Name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "房间名不能为空"})
		return
	}
	creatorIDStr := c.GetHeader("X-User-Id")
	creatorName := c.GetHeader("X-User-Name")
	if creatorIDStr == "" {
		creatorIDStr = c.Query("user_id")
	}
	if creatorName == "" {
		creatorName = c.Query("user_name")
	}
	creatorID, _ := strconv.Atoi(creatorIDStr)
	room := &models.Room{
			Name:        req.Name,
			CreatorID:   creatorID,
			CreatorName: creatorName,
			Tag:         req.Tag,
		}
		err := models.CreateRoom(room)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "房间创建失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"room_id": room.ID, "room_name": req.Name})
}

// GetRoomsHandler 获取房间列表
func GetRoomsHandler(c *gin.Context) {
	rooms, err := models.GetAllRooms()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取房间列表失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"data": rooms})
}

// DeleteRoomHandler 删除房间
func DeleteRoomHandler(c *gin.Context) {
	roomID := c.Param("id")
	if roomID == "" {
		roomID = c.Query("room_id")
	}
	if roomID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "房间ID不能为空"})
		return
	}
	if err := models.DeleteRoomByID(roomID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除房间失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "房间删除成功"})
}

// SetRoomEmptySinceHandler 设置房间为空的时间
func SetRoomEmptySinceHandler(c *gin.Context) {
	roomID := c.Param("id")
	if roomID == "" {
		roomID = c.Query("room_id")
	}
	t := time.Now()
	if err := models.SetRoomEmptySince(roomID, t); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "设置失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "设置成功"})
}

// ClearRoomEmptySinceHandler 清空房间为空的时间
func ClearRoomEmptySinceHandler(c *gin.Context) {
	roomID := c.Param("id")
	if roomID == "" {
		roomID = c.Query("room_id")
	}
	if err := models.ClearRoomEmptySince(roomID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "清空失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "清空成功"})
}
